package org.monkey.request.plugin.config;

import lombok.extern.slf4j.Slf4j;
import org.monkey.request.plugin.advisor.RequestLogAdvisor;
import org.monkey.request.plugin.aspect.TimeAnalyseAspect;
import org.monkey.request.plugin.handler.DefaultRequestLogAfterHandler;
import org.monkey.request.plugin.handler.DefaultRequestLogPreHandler;
import org.monkey.request.plugin.service.RequestLogHandleContext;
import org.springframework.boot.autoconfigure.AutoConfiguration;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;

@Slf4j
@AutoConfiguration
@ConditionalOnProperty(prefix = "request-log", name = "enable", havingValue = "true", matchIfMissing = true)
@EnableConfigurationProperties({RequestLogConfigProperty.class})
public class RequestLogAutoConfigBean {

  @ConditionalOnMissingBean(RequestLogHandleContext.class)
  @Bean
  public RequestLogHandleContext requestLogHandleContext() {
    log.info("request log service have init...");
    RequestLogHandleContext requestLogHandleContext = new DefaultRequestLogHandleContext();
    requestLogHandleContext.addAfterHandlerHead(new DefaultRequestLogAfterHandler());
    requestLogHandleContext.addPreHandlerLast(new DefaultRequestLogPreHandler());
    return requestLogHandleContext;
  }


  @ConditionalOnProperty(prefix = "request-log", name = "logEnable", havingValue = "true", matchIfMissing = true)
  @Bean
  public RequestLogAdvisor resLogAdvisor(RequestLogHandleContext requestLogHandleContext,RequestLogConfigProperty requestLogConfigProperty) {
    log.info("request aspect have init...");
    return new RequestLogAdvisor(requestLogHandleContext,requestLogConfigProperty.getExpress());
  }

  @ConditionalOnProperty(prefix = "request-log", name = "timeEnable", havingValue = "true", matchIfMissing = true)
  @Bean
  public TimeAnalyseAspect timeAnalyseAspect() {
    log.info("time aspect service have init...");
    return new TimeAnalyseAspect();
  }

}
